# 3.7 Ultrasonic Sensor ## 3.7.1 Overview Ultrasonic sensor measures the distance of an object by sound waves. It boasts a transmitter and a receiver to emit sound waves and then measure the returned waves. The time difference between transmitting and receiving can be used to calculate the distance value. Beyond that, it is also used to detect the shape or presence of objects, build automatic doors, and measure flow rates and pressures. ## 3.7.2 Schematic Diagram ![6-7](./media/6-7-2.png) **Working principle:** Like bats, the ultrasonic sensor sends an ultrasonic signal with a high frequency that human cannot hear. If these signals encounter obstacles, they will immediately reflect back and be received by the sensor. After that, the distance between the sensor and the obstacle is calculated according to the time difference between signals transmitting and receiving. **Maximum detection distance:** 3M **Minimum detection distance:** 4cm **Detection angle:** no greater than 15 degrees ## 3.7.3 Code Blocks ![j26](./media/j26.png) This block reads the distance value. You can modify its unit into cm (default) or inch. ## 3.7.4 Test Code ## 3.7.4.1 Build Code There are two ways to upload the code: directly open the code file we provide; or manually build blocks. **Directly open the code file we provide:** 1. Click ![](./media/j68.png) and choose `Load from your computer` ![](./media/j67.png) 2. We have already downloaded the codes on computer desktop, so open the file and choose `3-7-ultrasonic.sb3` **Manually build blocks:** 1. In ![events](./media/events.png), find ![j1](./media/j1.png) block. 2. In ![serial](./media/serial.png), find ![j12](./media/j12.png) block and set baud rate to 9600, and put it under ![j1](./media/j1.png). 3. In ![control](./media/control.png), put ![j2](./media/j2.png) under ![6-4-4-1-1](./media/6-2-4-1-1.png) ![6-2](./media/6-2-4-1-2.png) 4. In ![serial](./media/serial.png), put ![j13](./media/j13.png) in the block ![j2](./media/j2.png) and set the printing content to “Distance:” in no-warp mode. ![6-7](./media/6-7-4-1-1.png) 5. In ![serial](./media/serial.png), put ![j13](./media/j13.png) under the block ![image-20240628092544675](./media/image-20240628092544675.png) 6. In ![6-7](./media/ultrason.png), put ![j26](./media/j26.png) into the printing content of ![j13](./media/j13.png). 7. At last add a delay of 0.5S for better observing results. **Complete Test Code** ![6-7](./media/6-7-4-1-2.png) ## 3.7.4.2 Test Result After uploading code, the serial monitor prints the distance values and refreshes them per second. ![6-7](./media/6-7-4-2.png)